<template>
  <div class="todo-notice-set">
    <header>
      <tabs :tabs-arr="toDoTabList" @returnIndex="getTabIndex" />
    </header>
    <main>
      <div class="email-set">
        <el-button type="primary" class="set-btn" @click="emailSet"
          >邮箱设置</el-button
        >
      </div>
      <el-editable
        v-loading="loading"
        :data="tableData"
        :columns="tableColumn"
        @selection-change="handleSelectionChange"
        height="300"
      >
        <template slot="default-openStatus" slot-scope="{row}">
          <el-switch
            @change="updateStatus(row)"
            v-model="row.openStatus"
            :active-value="1"
            :inactive-value="0"
            active-text="开"
            inactive-text="关"
          >
          </el-switch>
        </template>
        <template slot="default-emailSeedStatus" slot-scope="{row}">
          <el-switch
            @change="updateStatus(row)"
            v-model="row.emailSeedStatus"
            :active-value="1"
            :inactive-value="0"
            active-text="开"
            inactive-text="关"
          >
          </el-switch>
        </template>
        <template slot="default-operation" slot-scope="{row}">
          <el-button type="text" size="small" @click="goDetail(row)"
            >查看
          </el-button>
        </template>
      </el-editable>
      <!-- 分页插件 -->
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-sizes="PAGE_NUMBER"
          :page-size="pageSize"
          :layout="PAGINATION_LAYOUT"
          :total="total"
        />
      </div>
    </main>
    <el-dialog
      custom-class="email-set"
      :title="isSet ? '添加邮箱' : '接收者详情'"
      :visible.sync="dialogVisible"
      width="60%"
    >
      <div class="email-set-wraper" v-if="isSet">
        <el-form
          :inline="true"
          v-for="(item, index) in emailSetList"
          :key="item.id + index"
        >
          <el-form-item>
            <span class="order-index"> {{ index + 1 }}</span>
          </el-form-item>
          <el-form-item label="接收者">
            <el-select
              v-model="item.userId"
              @change="getMailById(item)"
              placeholder="请选择"
            >
              <el-option
                v-for="ite in userOptions"
                :key="ite.userId"
                :label="ite.userName"
                :value="ite.userId"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="邮箱地址">
            <el-input v-model="item.mail" disabled />
          </el-form-item>
          <el-form-item label="">
            <span
              class="el-icon-circle-plus icon"
              v-show="index === emailSetList.length - 1"
              @click="addItem"
            ></span>
            <span
              v-show="emailSetList.length !== 1"
              class="el-icon-error icon"
              @click="deleteItem(item, index)"
            ></span>
          </el-form-item>
        </el-form>
      </div>
      <el-editable
        v-else
        :data="usertableData"
        :columns="usertableColumn"
        height="400"
      />
      <span slot="footer" class="dialog-footer">
        <template v-if="isSet">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitEmail">确定</el-button>
        </template>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import tabs from '@components/tabs/tabTool'
import ElEditable from '@components/el-editable/index.vue'
import {PAGINATION_LAYOUT, PAGE_NUMBER} from '@const/common.js'
import {tableColumn, toDoTabList, usertableColumn} from './const'
import {
  DcWorkbenchNoticeConfigpageList,
  DcWorkbenchNoticeConfigUpdate,
  DcWorkbenchConfigUserList,
  DcWorkbenchConfigUserSave,
} from '@const/mDataCenterApi'
import {getMerchantUserList} from '@const/api_staffCenter'
export default {
  name: 'TodoNoticeSet',
  data() {
    return {
      configType: 1,
      emailSetList: [],
      userOptions: [],
      toDoTabList,
      tableColumn,
      usertableColumn,
      tableData: [{}],
      usertableData: [{}],
      multipleSelection: [],
      loading: false,
      dialogVisible: false, // 弹窗控制
      isSet: true, // 是否是邮箱设置
      PAGE_NUMBER, // 分页数字
      pageSize: PAGE_NUMBER[0], // 分页类型
      PAGINATION_LAYOUT, // 分页功能
      total: 0, // 分页的总共的条数
      page: 1, // 分页的绑定的数据
    }
  },
  components: {
    tabs,
    ElEditable,
  },
  created() {
    this.getTableData()
    this.getMerchantUserOptions()
  },
  methods: {
    // 根据id查询邮箱地址
    getMailById(row) {
      if (!row.userId) return
      // 判断是否存在重复的
      let ids = this.emailSetList.filter((it) => row.userId == it.userId) || []
      let isExist = ids.length > 1
      if (isExist) {
        row.userId = ''
        row.mail = ''
        this.$message.warning('不可以设置重复数据')
        return
      }
      let email = this.userOptions.find((item) => item.id === row.userId)
      row.mail = email ? email.mail : ''
    },
    // 获取接收者下拉
    getMerchantUserOptions() {
      this.$axios({
        method: 'get',
        url: getMerchantUserList,
      })
        .then(({data}) => {
          if (Object.is(data.code, '0')) {
            let options = data.payload || []
            options.forEach((ite) => (ite.userId = ite.id))
            this.userOptions = options
          } else {
            this.userOptions = []
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    // 开启 邮箱设置
    updateStatus({emailSeedStatus, openStatus, id}) {
      this.$axios({
        method: 'post',
        url: DcWorkbenchNoticeConfigUpdate,
        data: {
          id,
          emailSeedStatus,
          openStatus,
        },
      })
        .then(({data}) => {})
        .finally(() => {
          this.getTableData()
        })
    },
    // 获取列表数据
    getTableData() {
      this.loading = true
      this.$axios({
        method: 'post',
        url: DcWorkbenchNoticeConfigpageList,
        data: {
          configType: this.configType,
          page: this.page,
          pageSize: this.pageSize,
        },
      })
        .then(({data}) => {
          if (Object.is(data.code, '0')) {
            let content = data.payload.content || []
            this.tableData = content
            this.total = data.payload.totalElements
          } else {
            this.tableData = []
            this.total = 0
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    // 复选框选择设置邮箱
    handleSelectionChange(selection) {
      this.multipleSelection = selection
    },
    // tab 切换
    getTabIndex(index) {
      this.configType = index + 1
      this.page = 1
      this.getTableData()
    },
    // 邮箱设置
    emailSet() {
      if (!this.multipleSelection.length) {
        this.$message.warning('请勾选数据后进行邮箱设置！')
        return
      }
      let row =
        this.multipleSelection.length === 1
          ? this.multipleSelection[0]
          : [{mail: '', userId: ''}]
      if (this.multipleSelection.length === 1) {
        this.goDetail(this.multipleSelection[0], true)
      } else {
        this.emailSetList = [{mail: '', userId: ''}]
      }
      this.isSet = true
      this.dialogVisible = true
    },
    // 提交前处理参数
    getParamsForSubmit() {
      let userIds = this.emailSetList.filter((item) => item.userId) || []
      let params = this.multipleSelection.map((ite) => {
        let empty = {}
        empty.noticeConfigId = ite.id
        empty.type = ite.type
        empty.userIds = userIds.map((i) => i.userId) || []
        return empty
      })
      return params
    },
    // 保存邮箱接收者
    submitEmail() {
      let userIds = this.getParamsForSubmit()
      this.$axios({
        method: 'post',
        url: DcWorkbenchConfigUserSave,
        data: userIds,
      }).then(({data}) => {
        if (data.code === '0') {
          this.$message.success('保存成功！')
          this.page = 1
          this.getTableData()
          this.dialogVisible = false
        }
      })
    },
    // 删除邮箱接收者
    deleteItem(item, index) {
      if (this.emailSetList.length > 1) {
        this.emailSetList.splice(index, 1)
      }
    },
    // 新增邮箱接收者
    addItem() {
      let newObj = {
        mail: '',
        userId: '',
      }
      this.emailSetList.push(newObj)
    },
    // 查看
    goDetail(row, isSet) {
      this.isSet = isSet ? true : false
      this.$axios({
        method: 'post',
        url: DcWorkbenchConfigUserList,
        data: {
          noticeConfigId: row.id,
        },
      }).then(({data}) => {
        if (data.code === '0') {
          this.emailSetList = isSet
            ? data.payload.content || [{mail: '', userId: ''}]
            : []
          this.usertableData = isSet ? [] : data.payload.content || []
          this.dialogVisible = true
          return
        }
        this.usertableData = []
      })
    },
    // 分页方法
    handleCurrentChange(curPage) {
      this.page = curPage
      this.getTableData()
    },
    // 分页页数
    handleSizeChange(pageSize) {
      this.page = 1
      this.pageSize = pageSize
      this.getTableData()
    },
  },
}
</script>

<style lang="less">
.email-set {
  .el-dialog__body {
    padding: 16px;
  }
}
.el-table__header .el-table-column--selection .cell .el-checkbox::after {
  content: '全选';
  margin-left: 5px;
}
</style>
<style scoped lang="less">
.todo-notice-set {
  display: flex;
  flex-direction: column;
  header {
    border-bottom: 1px solid #eef0f4;
    margin-bottom: 16px;
  }
  .order-index {
    display: inline-block;
    width: 24px;
  }
  main {
    display: flex;
    flex-direction: column;
    flex: 1;
    height: 100%;
    .email-set {
      .set-btn {
        float: right;
        margin-bottom: 8px;
      }
    }
    .pagination {
      width: 100%;
      text-align: right;
      margin: 10px 0;
    }
  }
  .email-set-wraper {
    max-height: 400px;
    overflow: auto;
    .icon {
      font-size: 28px;
      margin-top: 6px;
      cursor: pointer;
      color: #2066b1;
      &:last-child {
        color: red;
      }
    }
  }
}
</style>
